<?php

namespace App\Http\Controllers;


use App\Model\Image;
use App\Model\CityInfo;
use Illuminate\Http\Request;
use UpYun;
use UpYunException;

class CommonController extends Controller
{
    public function postImgUpload(Request $request)
    {
        $file = $request->file('upload_file');
        $from_editor = $request->input('from_editor', false);
        if ($file && $file->isValid()) {
            $mime = $file->getClientMimeType();
            $size = $file->getClientSize();
            $name = uniqid() . '.' . $file->guessExtension();
            $file->move('upload', $name);
            $image = new Image();
            $image->mime = $mime;
            $image->path = '/upload/' . $name;
            $image->size = $size;
            $image->tag = $request->input('tag', '');
            $image->save();

            if ($from_editor) {
                return response()->json(['success' => true, 'file_path' => '/uoload/' . $name]);
            } else {
                return $this->json_success('/upload/' . $name);
            }
        } else {
            return $this->json_error('上传了无效文件！', 1001);
        }
    }

    public function postImgUploadUpyun(Request $request)
    {

        require_once(app_path() . '/Library/' . "Upyun/upyun.class.php");

        $file = $request->file('upload_file');
        $from_editor = $request->input('from_editor', false);
        if ($file && $file->isValid()) {

            $upyun = new UpYun(config('upload.upyun.bucketname'), config('upload.upyun.username'), config('upload.upyun.password'));

            $mime = $file->getClientMimeType();
            $size = $file->getClientSize();
            $name = uniqid() . '.' . $file->guessExtension();
            $image = new Image();
            $image->mime = $mime;
            $image->path = config('upload.url_pre') . '/uploads/' . $name;
            $image->size = $size;
            $image->tag = $request->input('tag', '');

            $path = '/uploads/' . $name;
            try {
                $fh = fopen($file, 'rb');
                $rsp = $upyun->writeFile($path, $fh, True); // 上传图片，自动创建目录
                fclose($fh);

                if ($rsp) {
                    $image->type = $rsp['x-upyun-file-type'];
                    $image->width = $rsp['x-upyun-width'];
                    $image->height = $rsp['x-upyun-height'];
                    $image->save();
                    //来自编辑器的图片上传有特定的返回格式！
                    if ($from_editor) {
                        return response()->json(['success' => true, 'file_path' => config('upload.url_pre') . $path]);
                    } else {
                        return $this->json_success(config('upload.url_pre') . $path);
                    }
                } else {
                    return $this->json_error('上传至图片服务器失败！', 1002);
                }

            } catch (UpYunException $e) {
                return $this->json_error('上传至图片服务器失败！' . $e->getCode() . ' ' . $e->getMessage(), 1003);
            }
        } else {
            return $this->json_error('上传了无效文件！', 1001);
        }
    }




    public  function  getWeather(Request $request)
    {

        $arr=$request->all();
        $city_id = $this->_getCityID($arr);
        if(!$city_id)
        {
            return $this->json_sys_error();
        }
        $ch = curl_init();
        $url = 'https://free-api.heweather.com/v5/weather?city='.$city_id.'&key='.config('app.weather_key');
        curl_setopt($ch , CURLOPT_URL , $url);
        curl_setopt($ch , CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        curl_close($ch);
        $res=json_decode($res,true);
//        dump($res);
        $param['now_tmp']=$res['HeWeather5']['0']['now']['tmp'];
        $param['date']=date('m/d',strtotime($res['HeWeather5']['0']['daily_forecast']['0']['date']));
        $param['max']=$res['HeWeather5']['0']['daily_forecast']['0']['tmp']['max'];
        $param['min']=$res['HeWeather5']['0']['daily_forecast']['0']['tmp']['min'];
        $param['cond']=$res['HeWeather5']['0']['now']['cond']['code'];
        $param['txt']=$res['HeWeather5']['0']['now']['cond']['txt'];
        return $this->json_success($param);
    }

    /**
     * 获取城市ID
     */
    public function getCity()
    {
        $ch = curl_init();
        $url='https://api.heweather.com/x3/citylist?search=allchina&key='.config('app.weather_key');
        curl_setopt($ch , CURLOPT_URL , $url);
        curl_setopt($ch , CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        $res=json_decode($res);
        foreach($res->city_info as $v)
        {
            $v->city_id=$v->id;
            $param=get_object_vars($v);
            CityInfo::create($param);
        }
    }

    private  function  _getCityID($arr)
    {
        $town=substr($arr['town'],0,-2);
        $city=substr($arr['city'],0,-2);
        $pro=substr($arr['pro'],0,-2);
        $obj=CityInfo::where('city',$city)->where('prov',$pro)->first();
        if($obj) return $obj->city_id;
        return false;
    }

}
